package com.chinameyer.workorders.controller;

import cn.hutool.core.lang.tree.Tree;
import com.chinameyer.workorders.dto.catalogue.AddCatalogueDTO;
import com.chinameyer.workorders.dto.catalogue.EditCatalogueDTO;
import com.chinameyer.workorders.service.CatalogueService;
import com.chinameyer.workorders.vo.CatalogueVO;
import com.xinmachong.response.ApiResponse;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author meyer@HongYe
 */
@RestController
@RequestMapping("/v1/catalogue")
@Validated
@CrossOrigin
public class CatalogueController {

    @Resource
    private CatalogueService catalogueService;


    @PostMapping("/add")
    public ApiResponse add(@RequestBody @Validated AddCatalogueDTO addCatalogueDTO) {
        boolean isExist = this.catalogueService.checkCatalogueIsExist(addCatalogueDTO);
        if (isExist) {
            return new ApiResponse(400,"当前目录已存在，请勿重复创建目录",0);
        }
        try {
            int catalogueId = this.catalogueService.addCatalogue(addCatalogueDTO);
            return new ApiResponse(200, "success", catalogueId);
        } catch (Exception e) {
            return new ApiResponse(400,"目录添加失败，请重新添加或者联系系统管理员",0);
        }
    }


    @DeleteMapping("/delete")
    public ApiResponse delete(@RequestParam(value = "catalogueId") Integer catalogueId) {
        try {
            this.catalogueService.deleteCatalogue(catalogueId);
            return new ApiResponse(200, "success", 1);
        } catch (Exception e) {
            return new ApiResponse(400,"目录删除失败",0);
        }
    }


    @PostMapping("/update")
    public ApiResponse update(@RequestBody @Validated EditCatalogueDTO editCatalogueDTO) {
        boolean isExist = this.catalogueService.checkCatalogueIsExistExpectItself(editCatalogueDTO);
        if (isExist) {
            return new ApiResponse(400,"当前目录已存在，请更换目录名称",0);
        }
        try {
            this.catalogueService.updateCatalogue(editCatalogueDTO);
            return new ApiResponse(200, "success", 1);
        } catch (Exception e) {
            return new ApiResponse(400,"目录更新失败，请重新更新或者联系系统管理员",0);
        }
    }


    @GetMapping("/getAll")
    public ApiResponse getAll() {
        List<Tree<String>> catalogueVOS = this.catalogueService.getAllCatalogue();
        return new ApiResponse(200,"success",catalogueVOS);
    }
}
